<template>
  <div class="carousel-group">
    <main class="main">
      <div>
        <a-button
          type="primary"
          class="editable-add-btn"
          @click="showModal('add')"
          icon="plus"
        >
          新增
        </a-button>
        <a-table
          bordered
          :data-source="groupList"
          :columns="datasFomat"
          :rowKey="(record) => record.id"
          :pagination="false"
        >
          <template slot="createdAt" slot-scope="text, record">
            <span>{{ record.createdAt }}</span>
          </template>
          <!-- 操作 -->
          <template slot="operation" slot-scope="text, record">
            <a-popconfirm
              placement="bottom"
              title="确认删除？"
              ok-text="确认"
              cancel-text="取消"
              @confirm="delgroup(record.id)"
            >
              <a-button type="danger" icon="delete"> 删除 </a-button>
            </a-popconfirm>
            <a-button
              type="primary"
              @click="showModal('edit', record.id)"
              icon="edit"
            >
              编辑
            </a-button>
          </template>
        </a-table>
      </div>
    </main>
    <a-pagination
      class="pageTab"
      :current="current"
      :page-size-options="pageSizeOptions"
      :total="count"
      :show-total="(total) => `共 ${count} 个分类`"
      :page-size="limit"
      :default-current="1"
      show-size-changer
      @showSizeChange="onShowSizeChange"
      @change="pageChange"
    />
    <!-- 分组对话框 -->
    <a-modal
      :title="modalTitle"
      :visible="modalVisible"
      @ok="handleGroup"
      @cancel="closeModel"
    >
      <a-form-model :model="groupForm" ref="ruleForm" :rules="rules">
        <a-form-model-item label="轮播图分组" required prop="groupName">
          <a-input
            v-model.trim="groupForm.groupName"
            placeholder="首页-顶部"
          ></a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import {
  addCarouselGroupApi,
  editCarouselGroupApi,
  delCarouselGroupApi,
  getAllCarouselGroupListApi,
} from '@/services/webApi/carousel';
import moment from 'moment';
import { message } from 'ant-design-vue';

export default {
  data() {
    return {
      rules: {
        groupName: [
          {
            required: true,
            message: '请填写分组位置！',
            trigger: ['blur', 'change'],
          },
        ],
      },
      groupForm: {
        groupName: '',
      },
      datasFomat: [
        {
          title: '分组id',
          dataIndex: 'id',
          align: 'center',
          width: 100,
        },
        {
          title: '分组名',
          dataIndex: 'name',
          align: 'center',
          width: 200,
        },
        {
          title: '项目id',
          dataIndex: 'projectId',
          align: 'center',
          width: 100,
        },
        {
          title: '创建时间',
          dataIndex: 'createdAt',
          align: 'center',
          scopedSlots: {
            //  暴露作用域插槽
            customRender: 'createdAt', //   暴露作用域插槽名 向外暴露 当前行的值,数据，索引 text record index
          },
        },
        {
          title: '操作',
          align: 'center',
          scopedSlots: {
            customRender: 'operation',
          },
        },
      ],
      modalVisible: false,
      groupList: [],
      modalTitle: '',
      carouselGroupId: undefined,
      action: undefined, // 当前用户行为（新增/编辑）
      /* 分页相关 */
      current: 1, //当前页面
      pageSizeOptions: ['5', '10', '15', '20', '25'], //每页显示数量
      count: 0, //分组总数量
      limit: 5,
    };
  },
  created() {
    this.getGroupList();
  },
  methods: {
    // 获取轮播图分类列表
    async getGroupList(limit = 5, offset = 0) {
      let result = await getAllCarouselGroupListApi({
        limit,
        offset,
      });
      result.data.rows.forEach((ele) => {
        ele.createdAt = moment(ele.createdAt).format('YYYY-MM-DD  HH:mm:ss');
      });
      if (offset == 0) {
        this.current = 1;
      }
      this.groupList = result.data.rows;
      this.count = result.data.count;
    },
    // 删除分组
    delgroup(id) {
      delCarouselGroupApi({
        carouselGroupId: id,
      }).then((res) => {
        if (res.code === 200) {
          /* 请求成功 删除成功 */
          message.success(res.msg);
          // this.groupList = this.groupList.filter((item) => {
          //   return item.id != id;
          // });
          // this.count = this.groupList.length
          this.getGroupList(this.limit);
        } else {
          message.error(res.msg);
        }
      });
    },
    // 添加分组
    addGroup() {
      addCarouselGroupApi({ name: this.groupForm.groupName }).then(
        async (res) => {
          console.log(res);
          if (res.code !== 200) {
            return this.$message.error('创建失败');
          }
          message.success(res.msg);
          this.getGroupList(this.limit);
          setTimeout(() => {
            this.modalVisible = false;
            this.groupForm.groupName = '';
          }, 200);
        }
      );
    },
    // 编辑分组
    editGroup() {
      editCarouselGroupApi({
        name: this.groupForm.groupName,
        id: this.carouselGroupId,
      }).then(async (res) => {
        res.code != 200;
        if (res.code != 200) {
          return this.$message.error('编辑失败');
        }
        message.success(res.msg);
        let offset = (this.current - 1) * this.limit;
        this.getGroupList(this.limit, offset);
        setTimeout(() => {
          this.modalVisible = false;
          this.groupForm.groupName = '';
        }, 200);
      });
    },
    // modal框
    showModal(action, id = undefined) {
      this.action = action;
      switch (action) {
        case 'add':
          this.modalTitle = '新增分组';
          break;
        case 'edit':
          this.modalTitle = '编辑分组';
          this.carouselGroupId = id;
          break;
      }
      this.modalVisible = true;
    },
    // 编辑或添加
    handleGroup() {
      this.modalVisible = false;
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // 参数验证通过 发送请求
          switch (this.action) {
            case 'add':
              this.addGroup();
              break;
            case 'edit':
              this.editGroup();
              break;
          }
        } else {
          return message.warning('位置没有填写或格式错误！');
        }
      });
    },
    closeModel() {
      this.modalVisible = false;
      this.groupForm.groupName = '';
    },
    /*分页 */
    onShowSizeChange(current, pageSize) {
      this.limit = pageSize;
      this.pageChange(current);
    },
    pageChange(current) {
      this.current = current;
      let offset = (this.current - 1) * this.limit;
      this.getGroupList(this.limit, offset);
    },
  },
};
</script>

<style lang="scss" scoped>
.editable-cell {
  position: relative;
}

.editable-cell-input-wrapper,
.editable-cell-text-wrapper {
  padding-right: 24px;
}

.editable-cell-text-wrapper {
  padding: 5px 24px 5px 5px;
}

.editable-cell-icon,
.editable-cell-icon-check {
  position: absolute;
  right: 0;
  width: 20px;
  cursor: pointer;
}

.editable-cell-icon {
  line-height: 18px;
  display: none;
}

.editable-cell-icon-check {
  line-height: 28px;
}

.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}

.editable-cell-icon:hover,
.editable-cell-icon-check:hover {
  color: #108ee9;
}

.editable-add-btn {
  margin-bottom: 8px;
}

button {
  margin-right: 10px;
}
</style>
